package com.cangheng.app.util.threadTest;

public class DrawThread extends Thread{

	// 模拟用户账号
	private Account account;
	private double drawAmount;
	
	public DrawThread(String name, Account account, double drawAmount){
		super(name);
		this.account = account;
		this.drawAmount = drawAmount;
	}
	
	// 当多个线程改同一个共享数据时，将涉及数据安全问题
	@Override
	public void run() {
		// 使用 account作为同步监视器，任何线程进入下面同步代码块之前
		// 必须先获得对 account账户的锁定————其他线程无法获得锁，也就无法修改它
		// 这种做法符合：“加锁 -> 修改 -> 释放锁”的逻辑
		synchronized (account) {
			// 账户余额大于取钱数目
			if (account.getBalance() >= drawAmount) {
				// 吐出钞票
				System.out.println(getName() + "取钱成功" + drawAmount);
				
				// 修改余额
				account.setBalance(account.getBalance() - drawAmount);
				System.out.println(getName() + "余额为: " + account.getBalance());
			}
			else {
				System.out.println(getName() + "余额不足！");
			}
		}// 同步代码块结束，该线程释放同步锁
	}
	
	// getter & setter
	public Account getAccount() {
		return account;
	}
	public void setAccount(Account account) {
		this.account = account;
	}
	public double getDrawAmount() {
		return drawAmount;
	}
	public void setDrawAmount(double drawAmount) {
		this.drawAmount = drawAmount;
	}
}
